package edu.hrbu.kwaidu.util;

import edu.hrbu.kwaidu.model.entity.SysMenu;

import java.util.ArrayList;
import java.util.List;

import static edu.hrbu.kwaidu.constant.SystemConstant.SYSTEM_MENU_PARENT_ID;


/**
 * @author xudengyu
 */
public class MenuUtil {
    public static List<SysMenu> buildTree(List<SysMenu> menuList) {
        List<SysMenu> treeList = new ArrayList<>();
        for (SysMenu parent : menuList) {
            if (SYSTEM_MENU_PARENT_ID.equals(parent.getParentId())) {
                treeList.add(findChildren(parent, menuList));
            }
        }
        return treeList;
    }

    private static SysMenu findChildren(SysMenu parent, List<SysMenu> treeList) {
        for (SysMenu child : treeList) {
            if (parent.getId().equals(child.getParentId())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }
}
